<template>
    <el-autocomplete
      class="inline-input"
      v-model="model"
      :fetch-suggestions="loadResult"
      :placeholder="placeholder"
      :clearable="clearable"
      @select="handleSelect"
      :disabled="disabled"
      :popper-class="popperClass"
    ><template slot-scope="{item}" v-if="$slots.default"><slot :item="item"></slot></template>
    </el-autocomplete>
</template>
<script>
import {codeProvider} from '../../../assets/js/provider.js'
export default {
    props : {
        value    : {type: null },
        disabled : {type:Boolean,default:false},
        codeType : {type:String ,default:''},
        condition: {type:Object,default:()=>{}},
        popperClass : {type:String ,default:''},
        clearable:{type:Boolean,defualt:false},
        placeholder : String
    },

    computed : {
        model :{
            get(){
                return this.val ? this.val : this.value;
            },
            set(val){
                this.val = val;
                this.$emit("input",val);
            }
        }
    },
    data(){
        return {
            val : this.value,
            result : [],
        }
    },
    methods:{
        handleSelect(val){
            this.$emit("change" ,val);
        },
        loadResult(qstr,callback){
           let arr =  qstr? this.result.filter(this.createFilter) : this.result;
           if(callback){
               callback(arr);
           }
        },
        createFilter(queryString) {
            return (r) => {
                return (r.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        initData(){
            codeProvider.getList(this.codeType,this.condition||{}).then(resp=>{
                this.result = (resp||[]).map(item=>{
                    item.value = item.text;
                    return item;
                });
            });
        }
    },
    created(){
        this.initData();
    }
}
</script>

